package com.aqie.seckill.controller;

import com.aqie.seckill.domain.User;
import com.aqie.seckill.redis.RedisService;
import com.aqie.seckill.redis.UserKey;
import com.aqie.seckill.result.CodeMsg;
import com.aqie.seckill.result.Result;
import com.aqie.seckill.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

@Controller
public class HelloController {
    @Autowired
    private UserService userService;

    @Autowired
    private RedisService redisService;


    @GetMapping("/hello")
    @ResponseBody
    public String hello(){
        return "seckill begin";
    }

    @GetMapping("/success")
    @ResponseBody
    public Result<String> success() {
        return Result.success("success");
    }

    @GetMapping("/error")
    @ResponseBody
    public Result<String> error(){
        return Result.error(CodeMsg.SERVER_ERROR);
    }

    @GetMapping("/thymeleaf")
    public String test(Model model){
        model.addAttribute("name", "aqie");
        return "test";
    }

    @GetMapping("testUser")
    @ResponseBody
    public User testUser(){
        User u1= new User();
        u1.setName("aqie");
        return u1;
    }

    // 测试查询
    @RequestMapping("/db/get")
    @ResponseBody
    public Result<User> dbGet() {
        User user = userService.getById(1);
        return Result.success(user);
    }

    // 测试事务
    @RequestMapping("/db/tx")
    @ResponseBody
    public Result<Boolean> dbTx() {
        userService.tx();
        return Result.success(true);
    }

    // 测试 redis
    @RequestMapping("/redis/get")
    @ResponseBody
    public Result<User> redisGet() {
        User  user  = redisService.get(UserKey.getById, ""+1, User.class);
        return Result.success(user);
    }

    @RequestMapping("/redis/set")
    @ResponseBody
    public Result<Boolean> redisSet() {
        User user  = new User();
        user.setId(1);
        user.setName("1111");
        redisService.set(UserKey.getById, ""+1, user);//UserKey:id1
        return Result.success(true);
    }
}
